﻿using MongoDB.Driver;
using Sustainalytics.Entities.RiskRatings;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ScreeningTool.Synchronization.Handlers.RiskRatings
{
    public class ComprehensiveResearchProfileHandler : ResearchProfileHandler<RiskRatingResearchProfile>, IHandler<RiskRatingResearchProfile>
    {
        public override ProjectionDefinition<RiskRatingResearchProfile> GetProjection(ProjectionDefinitionBuilder<RiskRatingResearchProfile> builder)
            => base.GetProjection(builder)
            .Include(x => x.ThemeScores)
            .Include(x => x.OverallBetaFactor);

        public override IEnumerable<ExtraElement> GetExtraElements(RiskRatingResearchProfile entity)
            => EnumerableExtensions.Concat(
                base.GetExtraElements(entity),
                entity.ThemeScores?.GetExtraElements(),
                entity.GetExtraElements());
    }

    public static class RiskRatingResearchProfileExtensions
    {
        public static IEnumerable<ExtraElement> GetExtraElements(this IEnumerable<ThemeScore> themeScores)
            => themeScores.SelectMany(x => new ExtraElementList
            {
                { $"{x.Theme}-Risk Score",            x.UnmanagedRisk        },
                { $"{x.Theme}-Managed Risk Score",    x.ManagedRisk          },
                { $"{x.Theme}-Management Gap Score",  x.ManagementGap        },
                { $"{x.Theme}-Manageable Risk Score", x.ManageableRisk       },
                { $"{x.Theme}-Management Score",      x.ManagementScore      },
                { $"{x.Theme}-Management Weight",     x.ManagementWeight     },
                { $"{x.Theme}-Exposure Score",        x.ExposureScore        },
                { $"{x.Theme}-Exposure Contribution", x.ExposureContribution },
            });

        public static IEnumerable<ExtraElement> GetExtraElements(this RiskRatingResearchProfile entity)
            => new ExtraElementList
            {
                { "Overall Beta", entity.OverallBetaFactor },
            };
    }
}
